package com.gxa.hotel.admin.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.hotel.admin.mapper.RoomOrderlistMapper;
import com.gxa.hotel.admin.service.RoomOrderlistService;
import com.gxa.hotel.core.pojo.vo.RoomOrderlistVO;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author gxa
 * @since 2022-07-22
 */
@Service
public class RoomOrderlistServiceImpl extends ServiceImpl<RoomOrderlistMapper, RoomOrderlistVO> implements RoomOrderlistService {

    @Override
    public void export(List<RoomOrderlistVO> list, HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet("住宿记录表");
        String fileName = "住宿记录表.xls";

        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");

        String[] headers = {"编号", "房型名称", "房号", "姓名","手机号","抵店时间","离店时间"};

        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int rowNum = 1;
        for (int i = 0; i < list.size(); i++) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(list.get(i).getRType());
            dataRow.createCell(2).setCellValue(list.get(i).getRId());
            dataRow.createCell(3).setCellValue(list.get(i).getRoName());
            dataRow.createCell(4).setCellValue(list.get(i).getRoPhone());
            Date roInTime = Date.from(list.get(i).getRoInTime().atZone( ZoneId.systemDefault()).toInstant());
            dataRow.createCell(5).setCellValue(dateFormat.format(roInTime));
            Date roOutTime = Date.from(list.get(i).getRoOutTime().atZone( ZoneId.systemDefault()).toInstant());
            dataRow.createCell(6).setCellValue(dateFormat.format(roOutTime));
            rowNum++;
        }

        //返回给前端下载
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());

    }
}
